package red.yancloud.www.ui.fragment


import android.app.Activity
import android.content.Intent
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.webkit.JavascriptInterface
import android.widget.TextView
import androidx.appcompat.widget.AppCompatEditText
import com.alibaba.fastjson.JSONObject
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import okhttp3.ResponseBody
import red.yancloud.www.R
import red.yancloud.www.base.BaseWebViewFragment
import red.yancloud.www.common.Constants
import red.yancloud.www.internet.api.RedCloudApis
import red.yancloud.www.internet.bean.RepositorySort
import red.yancloud.www.ui.activity.*
import red.yancloud.www.util.AppUtils
import red.yancloud.www.util.ToastUtils
import red.yancloud.www.util.UrlUtils

/**
 * @Org：www.shuhai.com(陕西书海网络科技有限公司)
 * @Author：风不会停息 on 2019/6/5 15:02
 * E_Mail：yh131412hys@163.com
 * Describe：知库
 * Change：
 * @Version：V1.0
 */
class RepositoryFragment : BaseWebViewFragment() {

    private val TAG = "RepositoryFragment"

    private lateinit var repositorySortEntity: RepositorySort
    private lateinit var mRepositoryFragmentSearchEt: AppCompatEditText

    override val layoutId: Int
        get() = R.layout.fragment_repository

    override fun initData() {
        super.initData()

        mUrl="${Constants.API_BASE_RED_CLOUD_URL}Index/zhiku"

        RedCloudApis.getInstance().getZhiKuAllSortData(object : Observer<ResponseBody> {
            override fun onComplete() {
            }

            override fun onSubscribe(d: Disposable) {
            }

            override fun onNext(t: ResponseBody) {

                val result = String(t.bytes())

                if (!TextUtils.isEmpty(result)) {

                    val parseObject = JSONObject.parseObject(result)
                    val code = parseObject.getString("code")
                    if (code == Constants.SYSTEM_OK) {

                        repositorySortEntity = RepositorySort()
                        repositorySortEntity.code=code

                        val dataArray = parseObject.getJSONArray("data")
                        val dataList = ArrayList<RepositorySort.DataBean>()
                        repeat(dataArray.size) {

                            val dataObject = dataArray[it] as JSONObject

                            val dataBean = RepositorySort.DataBean()
                            dataBean.id=dataObject.getIntValue("id")
                            dataBean.parent_id=dataObject.getString("parent_id")
                            dataBean.sort=dataObject.getIntValue("sort")
                            dataBean.name=dataObject.getString("name")

                            val childrenObject = dataObject.getJSONObject("children")
                            val childrenList = ArrayList<RepositorySort.DataBean.ChildrenBean>()
                            childrenObject.entries.forEach {

                                val childObject = it.value as JSONObject
                                childrenList.add(
                                    RepositorySort.DataBean.ChildrenBean(childObject.getIntValue("id"),childObject.getIntValue("parent_id"),
                                        childObject.getIntValue("sort"),childObject.getString("name")))
                            }
                            dataBean.children=childrenList

                            dataList.add(dataBean)
                        }

                        repositorySortEntity.data=dataList
                        repositorySortEntity.msg=parseObject.getString("msg")
                    }
                }
            }

            override fun onError(e: Throwable) {

            }
        })
    }

    override fun configView() {
        super.configView()

        mRefreshLayout.setEnableLoadMore(false)

        mRepositoryFragmentSearchEt = parentView.findViewById(R.id.repositoryFragment_search_et)

        initSearchEditText()
    }

    private fun initSearchEditText() {

//        在清单文件对应的Activity中添加如下属性，防止布局被软键盘顶上去 android:windowSoftInputMode="stateAlwaysVisible|adjustPan"
        mRepositoryFragmentSearchEt.setOnEditorActionListener(object : TextView.OnEditorActionListener {

            override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {

                if (actionId== EditorInfo.IME_ACTION_SEARCH) {

                    activity?.let { AppUtils.closeInoutDecorView(it) }

                    val keyword = mRepositoryFragmentSearchEt.text.toString().trim()
                    mRepositoryFragmentSearchEt.text!!.clear()
                    if (TextUtils.isEmpty(keyword)) {

                        ToastUtils.showToast("请输入搜索关键字")
                        return true
                    }

                    startActivity(Intent(mContext,RepositorySearchActivity::class.java).putExtra("keyword",keyword))
                    return true
                }
                return false
            }
        })
    }

    override fun addJavaScriptInterface() {

        mWebView.addJavascriptInterface(object : Any() {

            @JavascriptInterface
            fun loadData(){
                mHandler.post(object :Runnable{
                    override fun run() {
                        mWebView.loadUrl("javascript:waves(" + UrlUtils.makeJsonText() + ")")
                        if (!(mContext as Activity).isFinishing) {
                            loadingDialog.dismiss()
                        }
                    }
                })
            }

            /**
             * vkey：指定大页面
             * vtoclas：区分小分类
             */
            @JavascriptInterface
            fun gotopage(key: String,value: String) {
                mHandler.post {

                    if (repositorySortEntity.code!=Constants.SYSTEM_OK||repositorySortEntity.data.size<1) {

                        ToastUtils.showToast("分类数据获取异常，请稍后再试")
                    }

                    var position1:Int=-1
                    var position3:Int=-1
                    var position4:Int=-1
                    var position5:Int=-1
                    var position6:Int=-1
                    var position7:Int=-1
                    var position8:Int=-1

                    for (i in 0 until repositorySortEntity.data.size) {

                        val dataBean = repositorySortEntity.data[i]
                        if (dataBean.id==1) {

                            position1=i
                        }
                        if (dataBean.id==3) {

                            position3=i
                        }
                        if (dataBean.id==4) {

                            position4=i
                        }
                        if (dataBean.id==5) {

                            position5=i
                        }
                        if (dataBean.id==6) {

                            position6=i
                        }
                        if (dataBean.id==7) {

                            position7=i
                        }
                        if (dataBean.id==8) {

                            position8=i
                        }
                    }

                    when (value) {
//                        理论
                        "1" -> {

                            startRepositoryEntryList(value, position1)
                        }
//                        人物
                        "3" -> {

                            startRepositoryEntryList(value, position3)
                        }
//                        事件
                        "4" -> {

                            startRepositoryEntryList(value, position4)
                        }
//                        政治
                        "5" -> {

                            startRepositoryEntryList(value, position5)
                        }
//                        军事
                        "6" -> {

                            startRepositoryEntryList(value, position6)

                        }
//                        经济
                        "7" -> {

                            startRepositoryEntryList(value, position7)

                        }
//                        社会
                        "8" -> {

                            startRepositoryEntryList(value, position8)
                        }
//                        更多
                        "0" -> {

                            Log.d(TAG,repositorySortEntity.toString())

                            mContext!!.startActivity(Intent(mContext,RepositorySortActivity::class.java))
                        }
//                        热搜词条更多
                        "hot" -> {

                            startActivity(Intent(mContext, HotSearchEntryMoreActivity::class.java))
                        }
//                        知库词条更多
                        "entry" -> {

                            startActivity(Intent(mContext, RepositoryEntryMoreActivity::class.java))
                        }
//                        专家团队更多
                        "mjentry" -> {

                            startActivity(Intent(mContext, ExpertTeamMoreActivity::class.java))
                        }
//                        作者团队更多
                        "author" -> {

                            startActivity(Intent(mContext, AuthorTeamMoreActivity::class.java))
                        }
                    }
                }
            }

            @JavascriptInterface
            fun gotourl(url: String,model: String,id: String) {
                mHandler.post {

//                    ToastUtils.showToast("$url----$model")

                    if (url.contains("mjentry")) {

                        startActivity(Intent(mContext, NewsInfoActivity::class.java)
                            .putExtra("url", Constants.BASE_RED_CLOUD_HOST_URL+url)
                            .putExtra("model",Constants.CollectModel.ZHIKUMJ)
                            .putExtra("id",id)
                        )
                    }else{

                        startActivity(Intent(mContext, NewsInfoActivity::class.java)
                            .putExtra("url", Constants.BASE_RED_CLOUD_HOST_URL+url)
                            .putExtra("model",model)
                            .putExtra("id",id)
                        )
                    }
                }
            }

            @JavascriptInterface
            fun alert(alert: String) {
                mHandler.post {

                    ToastUtils.showToast(alert)
                }
            }
        },"demo")
    }

    private fun startRepositoryEntryList(value: String, position: Int) {
        startActivity(
            Intent(mContext, RepositoryEntryListActivity::class.java)
                .putExtra("title",repositorySortEntity.data[position].name)
                .putExtra("cid", value.toInt())
                .putExtra("id", "")
                .putParcelableArrayListExtra(
                    "SortChildrenBean",
                    repositorySortEntity.data[position].children as java.util.ArrayList<RepositorySort.DataBean.ChildrenBean>
                )
        )
    }
}
